package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

var ip string
var port uint64
var name string
var space string
var group string
var namingClient naming_client.INamingClient

func init() {
	ip = getIP()
	flag.Uint64Var(&port, "p", 0, "register the port to nacos")
	flag.StringVar(&name, "n", "", "register the name project to nacos")
	flag.StringVar(&space, "s", "dev", "the NamespaceId of nacos`s ClientConfig")
	flag.StringVar(&group, "g", "dev", "register the GroupName project to nacos")
}

func main() {
	// 解析启动时传的值
	flag.Parse()
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
	waitElegantExit(ch)
	fmt.Println(port)
	clientConfig := constant.ClientConfig{
		TimeoutMs:      10 * 1000,
		ListenInterval: 30 * 1000,
		BeatInterval:   5 * 1000,
		//添加namespaceId来区分获取配置的环境
		NamespaceId: space,
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "nacos1.lanyuecloud.com",
			ContextPath: "/nacos",
			Port:        8848,
		},
		{
			IpAddr:      "nacos2.lanyuecloud.com",
			ContextPath: "/nacos",
			Port:        8848,
		},
		{
			IpAddr:      "nacos3.lanyuecloud.com",
			ContextPath: "/nacos",
			Port:        8848,
		},
	}
	var err error
	namingClient, err = clients.CreateNamingClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		fmt.Println(err)
	}

	success, _ := namingClient.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          ip,
		Port:        port,
		ServiceName: name,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		GroupName:   group,
	})
	fmt.Println("Register Result", success)

	ticker := time.NewTicker(time.Duration(1*60) * time.Second)
	go func() {
		for range ticker.C {
			url := "http://" + ip + ":" + strconv.FormatUint(port, 10)
			resp, err := http.Get(url)
			if err != nil || resp.StatusCode != 200 {
				deregister()
				os.Exit(2)
			}
			if err == nil {
				defer resp.Body.Close()
			}
		}
	}()

	<-ch
}

func getIP() string {
	var ip string
	resp, err := http.Get("http://icanhazip.com/")
	if err != nil {
		resp1, err := http.Get("http://ip.3322.net")
		if err != nil {
			fmt.Println("get ip err")
		}
		defer resp1.Body.Close()
		body1, _ := ioutil.ReadAll(resp1.Body)
		ip = string(body1)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	ip = strings.Replace(string(body), "\n", "", -1)
	return ip
}

// 优雅退出（退出信号）
func waitElegantExit(signalChan chan os.Signal) {
	go func() {
		<-signalChan
		deregister()
		os.Exit(2)
	}()
}
func deregister() {
	success, err := namingClient.DeregisterInstance(vo.DeregisterInstanceParam{
		Ip:          ip,
		Port:        port,
		ServiceName: name,
		Ephemeral:   true,
		GroupName:   group,
	})
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Deregister Register Result", success)
}
